const app = getApp();
let util = require('../../utils/util.js')
import * as API_Order from '../../api/order'
import { Foundation } from '../../ui-utils/index.js'

Page({
  data: {
    canReceive: false, // 支持优惠券领取
    order_sn: '', // 订单编号
    order: '', // 订单信息
    skuList:'', //规格列表
    num: 0 ,// 计算当前订单中的商品件数
    couponData: {} // 优惠券信息
  },
  onLoad: function (options) {
    // options为页面跳转所带来的参数页面初始化
    this.setData({order_sn: options.order_sn});
    // this.setData({order_sn: '20201026000011'});
  },
  onShow: async function () {
    let _isLogin = await app.isLogin();
    if (!_isLogin) { return };
    this.setData({
      order: '',
      skuList: '',
      num: 0,
    });
    this.getOrderDetail();
  },
  // 获取订单详情
  getOrderDetail: function () {
    API_Order.getShareOrderDetail(this.data.order_sn).then(res => {
      let { can_receive, coupon } = res;
      this.setData({
        canReceive: !!can_receive && coupon && (coupon.coupon_id || coupon.coupon_id ===0),
        couponData: coupon
      });
      let data = res.order_detail;
      const skuList = data['order_sku_list'];
      if(skuList && skuList.length){
        skuList.forEach(key=>{
          key.purchase_price = Foundation.formatPrice(key.purchase_price)
          if (!key.skuName) key.skuName = this.formatterSkuSpec(key)
          if(key && key.num){
            this.setData({
              num : this.data.num += key.num
            })
          }
        })
      };
      data.create_time = Foundation.unixToDate(data.create_time);
      data.ship_mobile = data.ship_mobile ? Foundation.secrecyMobile(data.ship_mobile) : '';
      if (data.leader && data.leader.leader_mobile) {
        data.leader.leader_mobile = Foundation.secrecyMobile(data.leader.leader_mobile);
      };
      this.setData({
        order: data,
        skuList: skuList
      });
    });
  },
  /** 规格格式化显示 */
  formatterSkuSpec(sku) {
    if (!sku.spec_list || !sku.spec_list.length) return ''
    return sku.spec_list.map(spec => spec.spec_value).join(' - ')
  },
  // 复制订单号
  orderCopy(e) {
    const orderSn = e.currentTarget.dataset.sn;
    wx.setClipboardData({
      data: orderSn,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '订单号复制成功'
            });
          }
        });
      }
    });
  },
  /** 去逛逛 */
  showIndex() {
    wx.switchTab({ url: '/pages/index-group/index/index' })
  },
  /** 隐藏优惠券弹框 */
  hideReceive() {
    console.log('333');
    this.setData({
      canReceive: false
    });
  }
});